#include<iostream>
#include<mysql.h>
#include"comm.hpp"

bool InsertSql(const std::string& sql) {

    //std::cout << "Version: " << mysql_get_client_info() << std::endl;

    //要链接MySQL首先要创建一个MySQL句柄
    MYSQL* mq = mysql_init(nullptr);

    //设置链接MySQL的编码格式(如果出现乱码，就设置为utf8)
    //mysql_set_character_set(mq, "utf8");

    //链接MySQL,后两个参数分别是域间套接字指针和链接标致
    if (mysql_real_connect(mq, "127.0.0.1", "http_client", "111111", "http_test", 3306, nullptr, 0) == nullptr) {
        std::cerr << "Connect MySQL failed!" << std::endl;
    }

    //执行MySQL语句
    std::cerr << "Query: " << sql << std::endl;
    int ret = mysql_query(mq, sql.c_str());
    std::cerr << "result: " << ret << std::endl;

    mysql_close(mq);
}

int main() {

    std::string parameter;
    //from http
    if (GetParameter(parameter)) {
        
        //数据处理
        std::string p1;
        std::string p2;
        Util::CutString(parameter, p1, p2, "&");

        std::string name;
        std::string password;
        std::string excess;
        Util::CutString(p1, excess, name, "=");
        Util::CutString(p2, excess, password, "=");

        //插入数据库
        std::string sql = "insert into user (name, password) values ('";
        sql.append(name);
        sql.append("', '");
        sql.append(password);
        sql.append("')");

        //std::cerr << sql << std::endl;

        if (InsertSql(sql)) {
            std::cout << "<html>";
            std::cout << "<head><meta charset=\"utf-8\"></head>";
            std::cout << "<body><h1>注册成功！</h1></body>";
            std::cout << "";
        }
    }
    return 0;
}